import * as api from '../../utils/api.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],
    productList: [],
    currentIndex: 0,
    currentCategoryId: 0,
  },
  switchNav: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    if (this.data.currentCategoryId == id) {
      return false;
    } else {
      const currentIndex = that.data.categoryList.findIndex(item => item.id == id)
      that.setData({
        currentCategoryId: id,
        currentIndex
      });
      this.getProductList(id)
    }
  },
  nextcombox: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/product/details?id=' + id,
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getProductCategoryList()
  },
  // onLoad: function(options) {
  //   var that = this
  //   wx.getSystemInfo({
  //     success: function(res) {
  //       that.setData({
  //         winHeight: res.windowHeight
  //       });
  //     }
  //   });
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  scrollToLower() {
    this.getProductList(this.data.currentCategoryId)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  getProductCategoryList() {
    const that = this
    api.productCategoryList()
      .then(res => {
        const categoryList = res.data
        let currentCategoryId = 0
        if (categoryList.length > 0) {
          currentCategoryId = categoryList[0].id
        }
        that.setData({
          categoryList,
          currentCategoryId
        })
        that.getProductList(currentCategoryId)
      }).catch(err => console.log(err))
  },
  getProductList(categoryId) {
    const that = this
    let productList = that.data.productList
    if (productList[categoryId]) {
      let list = productList[categoryId]['data'];
      const current_page = productList[categoryId]['current_page'];
      const last_page = productList[categoryId]['last_page'];
      if (current_page == last_page) {
        return false
      }
      api.productList(categoryId, current_page + 1)
        .then(res => {
          const data = res.data
          list = list.concat(data.data)
          productList[categoryId]['data'] = list;
          productList[categoryId]['current_page'] = data.current_page
          that.setData({
            productList
          })
        }).catch(err => console.log(err))
    } else {
      api.productList(categoryId, 1)
        .then(res => {
          productList[categoryId] = res.data
          that.setData({
            productList
          })
        }).catch(err => console.log(err))
    }
  }
})